//
//  LoginHelper.swift
//  Swift_SendMessage
//
//  Created by lanou on 15/11/25.
//  Copyright © 2015年 changfengZhang. All rights reserved.
//

import UIKit

class LoginHelper: NSObject {

    //登录方法
    func loginWithUser(userName : String, passWord : String) {
        
        PFUser.logInWithUsernameInBackground(userName, password: passWord) { (MyUser, error) -> Void in
            
            if MyUser != nil && error == nil {
                
                //发送一个登录成功的通知
//                let notification = NSNotificationCenter.defaultCenter()
//                
//                notification.postNotificationName("loginSucceed", object: nil)
                //as 代表一次类型的转换
                //as！代表前面可以为空
                //as？代表前面一定不能为空
                let app = UIApplication.sharedApplication().delegate as! AppDelegate
                
                let messageVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("messageVC")
                
                let naiVC = UINavigationController.init(rootViewController : messageVC)
                
                app.window?.rootViewController = naiVC
                
                UserManaged.defaultManager().saveUser(userName, userId: (MyUser?.objectId)!)
                
                //使用NSUserDefaults存储东西的方法
                let user = NSUserDefaults.standardUserDefaults()
                
                user.setObject(userName, forKey: "userName")
                
                user.setObject(MyUser?.objectId, forKey: "userId")
                
            }
           
        }
        
    }
    
    //注册方法
    func registerWithUser(userName : String, passWord : String) {
        
        let user = PFUser()
        
        user.password = passWord
        user.username = userName
        
        user.signUpInBackgroundWithBlock { (succeed, error) -> Void in
            
            if succeed {
                //当注册成功的时候，自动登录
                self.loginWithUser(userName, passWord: passWord)
                
            }
            
        }
        
    }
    
}
